﻿using System;
using EPiServer.BaseLibrary.Scheduling;
using EPiServer.PlugIn;
using EPiServer.Web.Hosting;

namespace EPiServer.Labs.MobilePack.Core
{
    [ScheduledPlugIn(DisplayName = "MobilePack Image Cache", Description = "Job that by default deletes all cached images that are 7 days or older")]
    public class ImageCacheJob : JobBase
    {
        private bool _stop;

        public ImageCacheJob()
        {
            IsStoppable = true;
        }

        public override string Execute()
        {
            int count = 0;

            string virtualImageCacheName = MobilePackSection.CurrentSection.VirtualImageCacheName;

            if (MobilePackSection.CurrentSection.DisableServerImageResizing)
            {
                return "Server side image resizing is disabled in web.config";
            }

            if (string.IsNullOrEmpty(virtualImageCacheName))
            {
                return "Missing virtualImageCacheName in MobilePack configuration";
            }

            var provider = (VirtualPathUnifiedProvider)VirtualPathHandler.GetProvider(virtualImageCacheName);

            var rootFolder = (UnifiedDirectory)provider.GetDirectory(provider.VirtualPathRoot);

            rootFolder.BypassAccessCheck = true;

            UnifiedFile[] allImages = rootFolder.GetFiles();

            int lifetimeImageCache = MobilePackSection.CurrentSection.LifetimeImageCache;

            if (lifetimeImageCache == 0)
            {
                lifetimeImageCache = 7;
            }

            foreach (var image in allImages)
            {
                if (this._stop)
                {
                    return string.Format("Stopped after deleting: {0} images", count);
                }

                if (DateTime.Now.Subtract(image.Changed).Days > lifetimeImageCache)
                {
                    image.Delete();

                    count++;
                }
            }

            return string.Format("Completed after deleting: {0} images", count);
        }

        public override void Stop()
        {
            this._stop = true;
        }
    }
}